;!function (global,$){
    var S7BuyCli = function () {
        this.API = {
            addCategory: "/goods/category"
        }
    };

    S7BuyCli.prototype = {
        init: function () {
            global.App.init();
            $('.fast-form').parsley();
            const err = getUrlParam('err');
            if (err) {
                const errCode = parseInt(err);
                let errTitle = '操作失败';
                let errMsg = '未知错误';
                switch (errCode) {
                    case 1007:
                        errMsg = '分类已存在';
                        break;
                }
                $.extend($.gritter.options, {
                    position: "top-left"
                });
                $.gritter.add({
                    title: errTitle,
                    text: errMsg,
                    class_name: "color danger",
                });
            }
        },
        submitForm2Ajax: function(url,action){
            
            return false;
        },
        initAdminLogin:function(){
            var err = getUrlParam('err');
            if (err === '1') {
                alert('登录失败，账号或密码错误');
            }
            var loginForm = $('#loginForm');
            loginForm.parsley();
            loginForm.submit(function () {
                var password = $('#password').val();
                $('input[name="password"]').val(md5(password));
                return true;
            });
        },
        initLogin: function(){
            console.log("这是登录页面",this);
            var loginForm = $("#loginForm");
            loginForm.parsley();
            loginForm.submit(function () {
                const params = $(this).serializeArray();
                console.log("表单参数: ",params);
                const username = params[0].value;
                const password = params[1].value;
                const req = {username:username,password:md5(password)};
                console.log("登录请求参数: ",req);
                $.post('/admin/login',req,function (resp) {
                    console.log("返回值: ",resp);
                    if (resp.code === 0){
                        global.location.href = '/admin'
                    } else {
                        alert(resp.msg);
                    }
                });
               return false;
            });
        },
        initDrawCash: function(){
            $(global.document).on('click','.dropdown-item',function () {
                const id = $(this).attr('id');
                const info = /record-(\d+)-status-(\d)/.exec(id);
                if (info !== null) {
                    const recordInfo = {id:info[1],status:info[2]};
                    $.post("/admin/trading/draw-cash",recordInfo,function (data) {
                        var code = data.code;
                        if(code === 0){
                            global.location.reload(true);
                        }else{
                            alert(data.msg);
                        }
                    });

                }
            });
            const createForm = $("#form-create");
            createForm.parsley();
            createForm.submit(function () {
                const params = $(this).serialize();
                $.post("/admin/trading/draw-cash/create",params,function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            })
        },
        initCategory: function () {
            var addCategoryForm = $("#add-category-form");
            addCategoryForm.parsley();
            addCategoryForm.submit(function () {
                $.post("/admin/goods/category/add",$(this).serialize(),function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });

            var editCategoryForm = $(".edit-category");
            editCategoryForm.parsley();
            editCategoryForm.submit(function () {
                $.post("/admin/goods/category/update",$(this).serialize(),function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });
            $(global.document).on('click','.del-category',function () {
                var domId = $(this).attr('id');
                var categoryId = domId.match(/(?<=del-category-)\d+/)[0];
                $.post("/admin/goods/category/del",{id: categoryId},function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
            });
        },
        initSettlement: function(){

        },
        initGoodsGroup: function(){
            var formAddGroup = $('#form-groups-add');
            formAddGroup.parsley();
            formAddGroup.submit(function () {
                $.post("/admin/goods/group/add",$(this).serialize(),function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });
            var editCategoryForm = $(".form-groups-update");
            editCategoryForm.parsley();
            editCategoryForm.submit(function () {
                $.post("/admin/goods/group/update",$(this).serialize(),function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });
            $(global.document).on('click','.del-group',function () {
                var domId = $(this).attr('id');
                var groupId = domId.match(/(?<=del-group-)\d+/)[0];
                $.post("/admin/goods/group/del",{id: groupId},function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
            });
        },
        initGoodsList: function (config) {
            var categoryTree = config.categoryTree;
            var allGroup = config.allGroup;
            var gc = $('.goods-category');
            var gg = $('.goods-group');
            var filterGroupCom = $(".filter-group");
            var filterCategoryCom = $(".filter-category");
            for (var i = 0;i<gc.length;i++) {
                var categoryId = parseInt($(gc[i]).attr('category-id'));
                var defaultSelected = '';
                if (categoryId === -1) {
                    defaultSelected = 'selected'
                }
                var targetList = ['<option value="-1" '+defaultSelected+'>无</option>'];
                this.deepTree(categoryTree,targetList,0,categoryId);
                // 处理分类树形结构
                var target = this.listToString(targetList);
                $(gc[i]).append(target);
            }
            const findUrlParam = function(param){
                const reg = RegExp('(^|&)'+ param +'=([^&]*)(&|$)');
                const s = global.location.search.substr(1).match(reg);
                if (s != null){
                    return decodeURI(s[2]);
                }
                return null;
            };
            const filterName = findUrlParam('filter');
            const filterVal = findUrlParam('f-val');
            const gs = buildGoodsGroupDom(allGroup,[parseInt(filterVal)]);
            if (filterName === null) {
                gs.unshift('<option value="-1" selected>无</option>');
            }else if (filterName === 'group') {
                gs.unshift('<option value="-1">无</option>');
            }
            const targetFilterDom = this.listToString(gs);
            filterGroupCom.append(targetFilterDom);
            for (var v=0;v<gg.length;v++){
                var gdStr = $(gg[v]).attr('group-data');
                var s = JSON.parse(gdStr);
                var targetGroupDom = this.listToString(buildGoodsGroupDom(allGroup,s));
                $(gg[v]).append(targetGroupDom);
            }
            gg.select2({
                width: "100%",
                allowClear:true,
                placeholder: "请选择商品分组"
            });
            const filterGroup = filterGroupCom.select2({
                minimumResultsForSearch: -1,
                width: "100%",
                placeholder: "请选择商品分组"
            });
            const filterCategory = filterCategoryCom.select2({
                minimumResultsForSearch: -1,
                width: "100%",
                placeholder: "请选择商品分组"
            });
            filterGroupCom.change(function () {
                const v = filterGroupCom.val();
                let url = '/admin/goods/list';
                if (v !== '-1'){
                    url +='?filter=group&f-val='+v;
                }
                global.location.href = url;

            });
            $('.modal').on('hidden.bs.modal', function (e) {
                // do something...
                var domGoodsId = $(this).attr('id');
                var goodsId = domGoodsId.match(/edit-goods-(\d+)/)[1];
                var formDom = $('#form-edit-goods-'+goodsId)[0];
                formDom.reset();
            });

            var formEditGoods = $('.form-edit-goods');
            formEditGoods.submit(function () {
                console.info($(this).serialize());
                $.post("/admin/goods/update",$(this).serialize(),function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });
            $(global.document).on('click','#store-refresh',function () {
                var btn = $(this);
                btn.attr('disabled',true);
                $('.table-tools').append('<span id="syncTip">正在同步中...</span>');
                $.post("/admin/goods/list/sync",function (data) {
                    var code = data.code;
                    if(code === 0){
                        // btn.removeAttr("disabled");
                        $('#syncTip').replaceWith('<span id="syncTip">同步成功，正在刷新数据..</span>');
                        // alert(data.msg);
                        global.location.reload(true)
                    }else{
                        $(this).removeAttr("disabled");
                        $('#syncTip').replaceWith('<span id="syncTip">同步失败.</span>');
                        alert(data.msg);
                    }
                });
            })
        },
        initPayment: function(ops){
            var orderNum = ops.orderNum;
            var returnUrl = ops.returnUrl;
            $("#mod-wechat").on("hidden.bs.modal", function() {
                // wx_qrcodeCanvas.remove();
                var wx_qrcodeCanvas = document.getElementById("qrcode_c");
                if (wx_qrcodeCanvas) {
                    wx_qrcodeCanvas.remove();
                }
            });
            $("#mod-alipay").on("hidden.bs.modal", function() {
                // wx_qrcodeCanvas.remove();
                var wx_qrcodeCanvas = document.getElementById("qrcode_c");
                if (wx_qrcodeCanvas) {
                    wx_qrcodeCanvas.remove();
                }
            });
            var loop = function(){
                return function () {
                    setInterval(function(){
                        $.get('/api/order/state',{
                            order_num:orderNum
                        },function (resp) {
                            var code = resp.code;
                            if(code === 0){
                                var data = resp.data;
                                var state = data.state;
                                var orderNum = data['order_num'];
                                var extraNum = data['extra_num'];
                                var amount = data['amount'];
                                if (state === 1){
                                    if (returnUrl.length>0) {
                                        var url = `${returnUrl}?order_no=${orderNum}&extra_no=${extraNum}&amount=${amount}`;
                                        window.location.href=url;
                                    }else{
                                        window.close();
                                    }
                                }
                            }
                        })
                    },1000);
                }();
            };
            loop();
            $('#payment').submit(function () {
                var params = $(this).serialize();
                $.post("/cashier/pay",params,function (resp) {
                    var code = resp.code;
                    if(code === 0){
                        var data = resp.data;
                        var payWay = data.pay_way;
                        console.log(payWay);
                        var img = new Image();
                        var cd = ['<canvas id="qrcode_c" width="200" height="200">',
                            '</canvas>'].join();
                        if (payWay===2) {
                            console.log('weix');
                            $('.qrcode_w2').append(cd);
                            var wx_qrcodeCanvas = document.getElementById("qrcode_c");
                            var wx_ctx = wx_qrcodeCanvas.getContext("2d");
                            img.onload = function () {
                                wx_ctx.drawImage(img,0,0);
                                $('#mod-wechat').modal();
                            };
                            img.src = "data:image/png;base64,"+data['qrcode_data'];
                        }else if(payWay===1){
                            $('.qrcode_w1').append(cd);
                            var wx_qrcodeCanvas = document.getElementById("qrcode_c");
                            var wx_ctx = wx_qrcodeCanvas.getContext("2d");
                            img.onload = function () {
                                wx_ctx.drawImage(img,0,0);
                                $('#mod-alipay').modal();
                            };
                            img.src = "data:image/png;base64,"+data['qrcode_data'];
                        }
                    }else{
                        alert(resp.msg);
                    }
                });
                return false;
            });
        },
        initOrderInfo: function(ops){
            var orderNum = ops.orderNum;
            var returnUrl = ops.returnUrl;
            $("#mod-wechat").on("hidden.bs.modal", function() {
                // wx_qrcodeCanvas.remove();
                var wx_qrcodeCanvas = document.getElementById("wx_qrcode");
                if (wx_qrcodeCanvas) {
                    wx_qrcodeCanvas.remove();
                }
            });
            var loop = function(){
                return function () {
                    setInterval(function(){
                        $.get('/api/order/state',{
                            order_num:orderNum
                        },function (resp) {
                            var code = resp.code;
                            if(code === 0){
                                var data = resp.data;
                                var state = data.state;
                                var orderNum = data['order_num'];
                                var extraNum = data['extra_num'];
                                var amount = data['amount'];
                                if (state === 1){
                                    if (returnUrl.length>0) {
                                        var url = `${returnUrl}?order_no=${orderNum}&extra_no=${extraNum}&amount=${amount}`;
                                        window.location.href=url;
                                    }else{
                                        window.close();
                                    }
                                }
                            }
                        })
                    },1000);
                }();
            };
            // loop();
            $('#payment').submit(function () {
                var params = $(this).serialize();
                $.post("/cashier/pay",params,function (resp) {
                    var code = resp.code;
                    if(code === 0){

                        var data = resp.data;
                        var img = new Image();
                        var cd = ['<canvas id="wx_qrcode" width="200" height="200">',
                            '</canvas>'].join();
                        $('.qrcode_w').append(cd);
                        var wx_qrcodeCanvas = document.getElementById("wx_qrcode");
                        var wx_ctx = wx_qrcodeCanvas.getContext("2d");
                        img.onload = function () {
                            wx_ctx.drawImage(img,0,0);
                            $('#mod-wechat').modal();
                        };
                        img.src = "data:image/png;base64,"+data['qrcode_data'];
                    }else{
                        alert(resp.msg);
                    }
                });
                return false;
            });
        },
        initUser: function(config){
            var pageData = config.pageData;
            var targetDom = buildListDom(this.resolveUserList(pageData.records));
            $('tbody').append(targetDom);
            var formAddUser = $('#form-user-add');
            formAddUser.parsley();
            formAddUser.submit(function () {
                var p = $(this).serializeArray();
                var password  = md5(p[3].value);
                var params = {
                    userLevel: p[0].value,
                    userName: p[1].value,
                    phoneNumber: p[2].value,
                    password: password,
                    parentId:p[4].value
                };
                $.post("/admin/user/add",params,function (data) {
                    var code = data.code;
                    if(code === 0){
                        global.location.reload(true)
                    }else{
                        alert(data.msg);
                    }
                });
                return false;
            });
        },
        resolveUserList: function(userList){
            var temp = [];
            for (var i=0;i<userList.length;i++) {
                temp.push(buildUserItem(userList[i]));
            }
            return temp;
        },

        listToString: function(list){
            var s = '';
            for(var i=0;i<list.length;i++){
                s += list[i];
            }
            return s;
        },
        deepTree: function (treeData,target,deep,selectedId) {
            for (var i=0;i<treeData.length;i++) {
                var name = treeData[i].name;
                var id = treeData[i].id;
                var selected = '';
                if (deep > 0){
                    name = '|----&nbsp;' + name
                }
                if (selectedId === id) {
                    selected = 'selected'
                }
                target.push('<option value="'+id+'" '+selected+'>'+name+'</option>');
                if (treeData[i].children) {
                    this.deepTree(treeData[i].children,target,deep+1,selectedId)
                }
            }
        }
    };

    function buildUserItem(userItem) {
        const {monthOrderStat,regDate,regTime} = userItem;
        return '<tr><td>'+buildTableCheckbox()+'</td>' +
            '<td class="user-avatar cell-detail user-info">' +
                '<img class="mt-0 mt-md-2 mt-lg-0" src="/static/img/img-avatar-1.png" alt="Avatar">' +
                '<span>'+(userItem.userName?userItem.userName:'暂无昵称')+'</span>'+
                '<span class="cell-detail-description">ID:'+userItem.id+'</span>' +
            '</td>'+
            '<td>'+userItem.phoneNumber+'</td>'+
            '<td>'+((userItem.userLevel===1)?'高级代理商':(userItem.userLevel===2)?'代理商会员':'其他用户')+'</td>'+
            '<td>'+(userItem.parentNumber?userItem.parentNumber:'无')+'</td>'+
            '<td class="number">'+(userItem.childCount?userItem.childCount:'0')+'</td>'+
            '<td class="number">'+ '￥'+(moneyFormat(userItem.userBalance?userItem.userBalance:0))+'</td>'+
            '<td class="cell-detail">' +
                '<span>本月结算: ￥0.00</span>' +
                '<span class="cell-detail-description">累计结算: ￥0.00</span>' +
            '</td>'+
            '<td class="cell-detail">' +
                '<span>预估收益: ￥'+(moneyFormat(monthOrderStat?monthOrderStat.amount:0))+'</span>' +
                '<span class="cell-detail-description">成交订单: '+(monthOrderStat?monthOrderStat.countNum:0)+'</span>' +
            '</td>' +
            '<td class="cell-detail">' +
                '<span>'+(regDate)+'</span>' +
                '<span class="cell-detail-description">'+(regTime)+'</span>' +
            '</td>' +
            '<td>' +
                '<button class="btn btn-rounded btn-space btn-success"' +
            ' data-toggle="modal">详情</button>'+
            '<button class="btn btn-rounded btn-space btn-danger"' +
            ' data-toggle="modal">加入黑名单</button>'+
            '</td></tr>';
    }
    function moneyFormat(money) {
        var m = money.toString().split('.');
        if (m.length === 2) {
            return m[0].replace(/(\d)(?=(?:\d{3})+$)/g,'$1,') + '.' + m[1]
        }
        return m[0].replace(/(\d)(?=(?:\d{3})+$)/g,'$1,') + '.00';
    }
    function buildTableCheckbox() {
        return '<label class="custom-control custom-control-sm custom-checkbox">' +
            '<input type="checkbox" class="custom-control-input"><span class="custom-control-label"></span>' +
            '</label>'
    }
    function buildListDom(list){
        var s = '';
        for(var i=0;i<list.length;i++){
            s += list[i];
        }
        return s;
    }
    function buildGoodsGroupDom(allGroup,s) {
        var target = [];
        for (var i = 0; i < allGroup.length; i++) {
            target.push(function(group){
                var se = '';
                if (findGroupSelected(s,group.id)) {
                    se = 'selected';
                }
                return '<option value="'+group.id+'" '+se+'>'+group.groupName+'</option>'
            }(allGroup[i]))
        }
        return target;
    }
    function buildGoodsGroupFilterDom() {
        var target = [];
    }
    const getUrlParam = function(param){
        var reg = RegExp('(^|&)'+ param +'=([^&]*)(&|$)');
        var s = global.location.search.substr(1).match(reg);
        if (s != null){
            return decodeURI(s[2]);
        }
        return null;
    };
    function findGroupSelected(allSelected,id) {
        if (allSelected === null) {
            return false;
        }
        for (var i=0;i<allSelected.length;i++){
            if (allSelected[i] === id) {
                return true;
            }
        }
        return false;
    }
    !('S7BuyCli' in global) && (global.S7BuyCli = S7BuyCli);
}(window,jQuery);
